package com.ldl.exam.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ldl.exam.constant.Constants;
import com.ldl.exam.service.StuService;
import com.ldl.exam.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/04 21:54:26
 */
@Slf4j
@Component
public class StuLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StuService stuService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath();
        log.debug(servletPath);
        Object stuLogin = request.getSession().getAttribute(Constants.STU_LOGIN_KEY);
        if(null == stuLogin) {
            // TODO: token 验证
//            Cookie[] cookies = request.getCookies();
//            if(null != cookies) {
//                for (Cookie cookie : cookies) {
//                    // 登录 token 验证
//                    if(Constants.LOGIN_TOKEN_KEY.equals(cookie.getName())) {
//
//                        // 成功后, 查询 Stu 存入 Session
//
//                    }
//                }
//            }

            String regex = ".*(\\.js|\\.css|\\.html)$";
            if(servletPath.matches(regex)) {
                request.getRequestDispatcher("/public/401.html").forward(request, response);
                return false;
            }

            // ajax 请求
            ObjectMapper mapper = new ObjectMapper();
            AjaxResult fail = AjaxResult.isFail("您还未登录！");
            fail.setStatus(401);
            String value = mapper.writeValueAsString(fail);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(value);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("请求已处理完成");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("即将完成响应");
    }
}
